package com.ruoyi.common.core.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class LatLngConverter {

    /**
     * 将度分秒格式的经纬度转换为数字类型
     *
     * @param degree 要转换的度分秒字符串，如：39°54'26.1"N
     * @return 经纬度的数字类型
     */
    public static BigDecimal convertDegreeToDecimal(String degree) {
        String[] strArr = degree.split("[^\\d\\.]+");
        int degreeNum = Integer.parseInt(strArr[0]);
        int minuteNum = Integer.parseInt(strArr[1]);
        BigDecimal secondNum = new BigDecimal(strArr[2]).setScale(6, RoundingMode.HALF_UP);
        String direction = degree.substring(degree.length() - 1);
        BigDecimal decimalNum = new BigDecimal(degreeNum).add(new BigDecimal(minuteNum).divide(new BigDecimal("60"), 6, RoundingMode.HALF_UP))
                .add(secondNum.divide(new BigDecimal("3600"), 6, RoundingMode.HALF_UP));
        if (direction.equals("S") || direction.equals("W")) {
            decimalNum = decimalNum.negate();
        }
        return decimalNum;
    }

    /**
     * 将数字类型的经纬度转换为度分秒格式
     *
     * @param decimalNum 要转换的经纬度数字类型
     * @return 经纬度的度分秒字符串
     */
    public static String convertDecimalToDegree(BigDecimal decimalNum) {
        int degreeNum = decimalNum.intValue();
        BigDecimal temp = decimalNum.subtract(new BigDecimal(degreeNum)).multiply(new BigDecimal("60"));
        int minuteNum = temp.intValue();
        BigDecimal secondNum = temp.subtract(new BigDecimal(minuteNum)).multiply(new BigDecimal("60")).setScale(1, RoundingMode.HALF_UP);
        String direction = decimalNum.compareTo(BigDecimal.ZERO) >= 0 ? "N" : "S";
        if (direction.equals("S")) {
            degreeNum = -degreeNum;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(degreeNum).append("°").append(minuteNum).append("'").append(secondNum).append("\"").append(direction);
        return sb.toString();
    }
}
